//
//  AVController.m
//  ZDAudioProcessing
//
//  Created by zhibao on 2023/11/3.
//

#import "CommPlayerController.h"
#import <AVFoundation/AVFoundation.h>
@interface CommPlayerController ()<UIDocumentInteractionControllerDelegate>{
    UILabel *playLeftTimeLabel;
    UILabel *playRightTimeLabel;
    UISlider *playSlider;
    UIButton *playbeishuBtn;
    UIButton *playPlayBtn;
    UIImageView *playTopImgView;
    UIView *playBottomView;
    AVPlayerItem *playItem;
    AVPlayerLayer * playLayer;
    CGFloat totalDuration;
}
@property(nonatomic,strong)AVPlayer *player;
@property (nonatomic,strong)UIDocumentInteractionController *document;
@property (nonatomic,strong)NSString *mp3filePath;
@end

@implementation CommPlayerController

- (void)viewDidLoad {
    [super viewDidLoad];
    totalDuration = 0;
    AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayAndRecord
               withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
                       error:nil];
    self.gk_navTitle = @"";
    //self.gk_navBackgroundColor = UIColor.clearColor;
    // AVPlayerItem是一个包装音乐资源的类，初始化时可以传入一个音乐的url
    if(self.type == CommPlayerLocalMp3 || self.type == CommPlayerLocalMp4){
        playItem = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:self.url]];
    }else{
        playItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.url]];
    }
    //通过AVPlayerItem初始化player
    _player = [[AVPlayer alloc] initWithPlayerItem:playItem];
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    __weak typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        float current = CMTimeGetSeconds(time);
        //strongSelf->playLeftTimeLabel.text = [Helper getHHmmssTime:(int)current];
        if (current) {
            if((int)current >= (int)strongSelf->totalDuration){
                [strongSelf->playPlayBtn setImage:[UIImage imageNamed:@"home_zh_start"] forState:UIControlStateNormal];
                strongSelf->playSlider.value = 0;
                [strongSelf.player seekToTime:CMTimeMake(0.1, 1)];
                [strongSelf.player pause];
                //[Helper pauseAnimation:strongSelf->playTopImgView];
                return;
            }
            float progress = current / self->totalDuration;
            //更新播放进度条
            strongSelf->playSlider.value = progress;
        }
    }];
    playLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    playLayer.frame = CGRectMake(0, NAVIH, MY_Screen_W, MY_Screen_H - NAVIH);
    UIView *tempView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:tempView];
    [tempView.layer addSublayer:playLayer];
    [self initView];
}

-(void)initView{
    playTopImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"file_mp3_top"]];
    [self.view addSubview:playTopImgView];
    [playTopImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(230 - 64 + NAVIH);
        make.centerX.equalTo(self.view);
    }];
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    //设置动画完成后保持原状
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    //值
    animation.fromValue = [NSNumber numberWithFloat:0];
    animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
        
    animation.repeatCount = MAXFLOAT;
    animation.duration = 2;
    [playTopImgView.layer addAnimation:animation forKey:@"transform"];

    
    if(self.type == CommPlayerUrlMp4 || self.type == CommPlayerLocalMp4){
        playTopImgView.hidden = YES;
    }else{
        playTopImgView.hidden = NO;
    }
    
    playBottomView = [[UIView alloc]initWithFrame:CGRectMake(15, SCREEN_HEIGHT - 20 - SafeBottomMargin - 135, MY_Screen_W - 30, 40)];
    playBottomView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:playBottomView];
    //playBottomView.hidden = YES;
    
    //播放
    playPlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [playPlayBtn setImage:[UIImage imageNamed:@"home_zh_pause"] forState:UIControlStateNormal];
    playPlayBtn.tag = 1002;
    [playPlayBtn addTarget:self action:@selector(daochuClick:) forControlEvents:UIControlEventTouchUpInside];
    [playBottomView addSubview:playPlayBtn];
    [playPlayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(playBottomView);
    }];
    
    playLeftTimeLabel = [UILabel new];
    playLeftTimeLabel.text = @"00:00";
    playLeftTimeLabel.textColor = UIColor.whiteColor;
    playLeftTimeLabel.textAlignment = NSTextAlignmentRight;
    playLeftTimeLabel.font = MY_SCALE_RegularFONT(11);
    [playBottomView addSubview:playLeftTimeLabel];
    [playLeftTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(playPlayBtn.mas_right).offset(10);
        make.centerY.equalTo(playPlayBtn);
        make.width.mas_offset(50);
    }];
    
    playRightTimeLabel = [UILabel new];
    playRightTimeLabel.text = @"00:00";
    playRightTimeLabel.textColor = UIColor.whiteColor;
    playRightTimeLabel.font = MY_SCALE_RegularFONT(11);
    [playBottomView addSubview:playRightTimeLabel];
    [playRightTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(playBottomView.mas_right);
        make.centerY.equalTo(playBottomView);
        make.width.mas_offset(50);
    }];
    
    playSlider = [[UISlider alloc]init];
    playSlider.maximumTrackTintColor =  MyColorAlpha(@"ffffff", 0.3);
    //playSlider.userInteractionEnabled = NO;
    playSlider.minimumTrackTintColor = UIColor.redColor;
    [playSlider addTarget:self action:@selector(playSliderStartChange:) forControlEvents:UIControlEventTouchDown];
    [playSlider addTarget:self action:@selector(playSliderValueChange:) forControlEvents:UIControlEventTouchUpInside];
    [playBottomView addSubview:playSlider];
    [playSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(playLeftTimeLabel.mas_right).offset(20);
        make.right.equalTo(playRightTimeLabel.mas_left).offset(-20);
        make.centerY.equalTo(playLeftTimeLabel);
    }];
}

-(void)startAnmation{
    
}

-(void)dealPlayClick{
    if(self.player.status == AVPlayerStatusReadyToPlay){
        if(self.player.timeControlStatus != AVPlayerTimeControlStatusPlaying){
            if(self.type == CommPlayerUrlMp3 || self.type == CommPlayerLocalMp3){
                playTopImgView.hidden = NO;
            }
            [self.player play];
            //[Helper resumeAnimation:playTopImgView];
            [playPlayBtn setImage:[UIImage imageNamed:@"home_zh_start"] forState:UIControlStateNormal];
        }
    }else{
        [QMUITips showError:LocalizedString(@"加载中")];
    }
}
-(void)btnClick:(UIButton *)sender{
    NSString *title = [sender titleForState:UIControlStateNormal];
    if([title isEqualToString:LocalizedString(@"导出")]){
        [self exportMP3:self.url];
    }else if([title isEqualToString:LocalizedString(@"移动")]){
        //移动
        if(_dealBlock){
            _dealBlock(CommPlayerDealTypeMove);
        }
    }else if([title isEqualToString:@"重命名"]){
        [Helper alertShowWithTitle:@"重命名" withSureBtnTitle:@"确定" withCancelBtnTitle:@"取消" withAnwer:^(NSString * _Nullable anwer) {
            if (anwer.qmui_trimAllWhiteSpace.length > 0) {
                //[Helper RenameWithUrl:self.partUrl withNewName:anwer.qmui_trimAllWhiteSpace withDocum:self.docum withType:self->_threeType];
                DLog(@"old==%@",self.url);
                self.url = [self.url stringByReplacingOccurrencesOfString:self.gk_navTitle withString:anwer.qmui_trimAllWhiteSpace];
                DLog(@"new==%@",self.url);
                self.partUrl = [self.partUrl stringByReplacingOccurrencesOfString:self.gk_navTitle withString:anwer.qmui_trimAllWhiteSpace];
                self.gk_navTitle = [self.gk_navTitle stringByReplacingOccurrencesOfString:self.gk_navTitle withString:anwer.qmui_trimAllWhiteSpace];
                self.na_title = [self.na_title stringByReplacingOccurrencesOfString:self.gk_navTitle withString:anwer.qmui_trimAllWhiteSpace];
            }
        }];
        //重命名
        if(_dealBlock){
            _dealBlock(CommPlayerDealTypeReName);
        }
    }else if([title isEqualToString:@"删除"]){
        //删除
        if(_dealBlock){
            _dealBlock(CommPlayerDealTypeDele);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


//滑动开始
- (void)playSliderStartChange:(UISlider *)sender
{
    if(self.player.status != AVPlayerStatusReadyToPlay){
        return;
    }
    [self.player pause];
    //[Helper pauseAnimation:playTopImgView];
}

//移动滑块调整播放进度
- (void)playSliderValueChange:(UISlider *)sender
{
    if(self.player.status != AVPlayerStatusReadyToPlay){
        return;
    }
  //根据值计算时间
  float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration);
  //跳转到当前指定时间
  [self.player seekToTime:CMTimeMake(time, 1)];
  [self.player play];
    //[Helper resumeAnimation:playTopImgView];
}

-(void)daochuClick:(UIButton *)sender{
    if(sender.tag == 1000){
        //导出
        if(self.type == CommPlayerUrlMp4 || self.type == CommPlayerUrlMp3){
            [self newLoadData:self.url];
        }else{
            [self exportMP3:self.url];
        }
    }else if(sender.tag == 1001){
        //倍速
        NSString *title = [sender titleForState:UIControlStateNormal];
        if([title isEqualToString:@"1X"]){
            [sender setTitle:@"2X" forState:UIControlStateNormal];
            self.player.rate = 2;
        }else if([title isEqualToString:@"2X"]){
            [sender setTitle:@"3X" forState:UIControlStateNormal];
            self.player.rate = 3;
        }else{
            [sender setTitle:@"1X" forState:UIControlStateNormal];
            self.player.rate = 1;
        }
    }else if(sender.tag == 1002){
        //播放按钮
        if(self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying){
            [self.player pause];
            //[Helper pauseAnimation:playTopImgView];
            [playPlayBtn setImage:[UIImage imageNamed:@"home_zh_start"] forState:UIControlStateNormal];
        }else{
            [self.player play];
            //[Helper resumeAnimation:playTopImgView];
            [playPlayBtn setImage:[UIImage imageNamed:@"home_zh_pause"] forState:UIControlStateNormal];
        }
    }else if(sender.tag == 1003){
        //左一首
        [QMUITips showInfo:@"开发中"];
    }else if(sender.tag == 1004){
        //又一首
        [QMUITips showInfo:@"开发中"];
    }
}

//观察者回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //注意这里查看的是self.player.status属性
    if ([keyPath isEqualToString:@"status"]) {
        
        switch (self.player.status) {
            case AVPlayerStatusUnknown:
            {
                NSLog(@"未知转态");
                break;
            }
                
            case AVPlayerStatusReadyToPlay:
            {
                NSLog(@"准备播放");
                [self.player play];
                [playPlayBtn setImage:[UIImage imageNamed:@"home_zh_pause"] forState:UIControlStateNormal];
                //总时间
                totalDuration = CMTimeGetSeconds(playItem.duration);
                //playRightTimeLabel.text = [Helper getHHmmssTime:(int)totalDuration];
                break;
            }
                
            case AVPlayerStatusFailed:
            {
                NSLog(@"加载失败");
                break;
            }
                
            default: break;
                
        }
    }else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSArray * timeRanges = self.player.currentItem.loadedTimeRanges;
        //本次缓冲的时间范围
        CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];
        //缓冲总长度
        NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
        //音乐的总时间
        NSTimeInterval duration = CMTimeGetSeconds(self.player.currentItem.duration);
        playRightTimeLabel.text = [NSString stringWithFormat:@"%d:%d",(int)duration / 60,(int)duration % 60];
        //计算缓冲百分比例
        NSTimeInterval scale = totalLoadTime/duration;
        
    }
}
#pragma mark - loadData

- (void)newLoadData:(NSString *)url {
    NSArray *urls = [url componentsSeparatedByString:@"/"];
    NSString *filePath = [[self videoFilePath] stringByAppendingPathComponent:urls.lastObject];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExists)
    {
        DLog(@"已经有了-----");
        BOOL flag =  [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
        DLog(@"flag==%d",flag);
    }
    
    __weak typeof(self) weakSelf = self;
    [QMUITips showLoadingInView:self.view];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        dispatch_async(dispatch_get_main_queue(), ^{
            DLog(@"进度：%f",downloadProgress.completedUnitCount*1.0/downloadProgress.totalUnitCount);
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        DLog(@"filePath==%@",filePath);
//        NSString *name = [[NSFileManager defaultManager] displayNameAtPath:self.movieURL.path];
//        NSString *savefilePath = [[self videoFilePath] stringByAppendingPathComponent:name];
//        [[NSFileManager defaultManager] moveItemAtPath:filePath.path toPath:savefilePath error:nil];
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.mp3filePath = filePath.absoluteString;
        [strongSelf exportMP3:filePath.absoluteString];
        [QMUITips hideAllTipsInView:self.view];
    }];
    
    [downTask resume];
    
}

-(void)exportMP3:(NSString *)url{
    NSURL *URL = [NSURL URLWithString:url];
    if(self.type == CommPlayerLocalMp4 || self.type == CommPlayerLocalMp3){
        URL = [NSURL fileURLWithPath:url];
    }
   
    _document = [UIDocumentInteractionController interactionControllerWithURL:URL];
    _document.delegate    =  (id)self;
    // 用户不预览文件直接分享，如图2所示
    BOOL canOpen = [self.document presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
    
    if(!canOpen) {
        NSLog(@"沒有程序可以打开选中的文件");
    }else{
        //[_document presentPreviewAnimated:YES];
    }
}

- (NSString *)videoFilePath {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"clockin_movie_file"];
    BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!isExists)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}


#pragma mark - ** UIDocumentInteractionController 代理方法 **
- (UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}
- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
    return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    return self.view.frame;
}

-(void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController*)controller{
    NSLog(@"dissMiss");
    BOOL flag1 =  [[NSFileManager defaultManager] removeItemAtPath:self.mp3filePath error:nil];
     DLog(@"flag1==%d",flag1);
}
- (void)backItemClick:(id)sender{
    [self.player pause];
    //[Helper pauseAnimation:playTopImgView];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [playLayer removeFromSuperlayer];
    playLayer = nil;
    self.player = nil;
    [super back];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.player pause];
    //[Helper pauseAnimation:playTopImgView];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [playLayer removeFromSuperlayer];
    playLayer = nil;
    self.player = nil;
    
}

- (void)dealloc{
    [self.player pause];
    //[Helper pauseAnimation:playTopImgView];
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    [self.player.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    [playLayer removeFromSuperlayer];
    playLayer = nil;
    self.player = nil;
}

@end
